package servlet.assitant;

import dao.domain.Book;
import service.AssistantService;
import service.BookService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author huangzhiyang
 * @Date 2023/9/20
 * @Description ${PACKAGE_name}
 */
@WebServlet(name = "BookEditServlet", value = "/BookEditServlet")
public class AssistantEditBookServlet extends HttpServlet {
    /**
     * 获取Book对象，如果有值为null，则保持原值
     *
     * @param request 获得的请求
     * @return 不从数据库获得，只是将获得的book数据实例化
     */
    public static Book getBook(HttpServletRequest request) {
        int number = Integer.parseInt(request.getParameter("number"));
        Book oBook;
        try {
            oBook = BookService.selectById(number);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        String name = getString(request, oBook, "name");
        String author = getString(request, oBook, "author");
        String publisher = getString(request, oBook, "publisher");
        String priceStr = getString(request, oBook, "price");
        double price = Double.parseDouble(priceStr);
        String quantityStr = getString(request, oBook, "quantity");
        int quantity = Integer.parseInt(quantityStr);

        return new Book(number, name, author, publisher, price, quantity);
    }

    private static String getString(HttpServletRequest request, Book oBook, String para) {
        String name = request.getParameter(para);
        if (name == null || name.isEmpty()) {
            name = oBook.getName();
        }
        return name;
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 2023/9/20 修改书籍信息
        Book book = getBook(request);
        String msg;
        try {
            AssistantService.modifyBook(book);
            msg = "{\"msg\":\"success\"}";
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        response.getWriter().write(msg);
        System.out.println("finish");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("BookEditServlet现在来了一个post请求，将要去走get的代码了。");
        doGet(request, response);
    }
}
